<template>
  <div class="game-container">
    <!-- 游戏头部 -->
    <div class="game-header">
      <div class="header-left">
        <el-button @click="backToLobby" type="info" size="large">
          <el-icon><ArrowLeft /></el-icon>
          返回大厅
        </el-button>
        
        <div class="room-info">
          <h2>{{ roomName }}</h2>
          <span class="room-code">{{ roomId }}</span>
        </div>
      </div>
      
      <div class="header-center">
        <GameTimer :duration="gameDuration" />
      </div>
      
      <div class="header-right">
        <div class="connection-status" :class="{ connected: isConnected }">
          <el-icon><Connection /></el-icon>
          {{ isConnected ? '已连接' : '未连接' }}
        </div>
      </div>
    </div>

    <!-- 游戏主体 -->
    <div class="game-main">
      <!-- 左侧玩家列表 -->
      <div class="game-sidebar">
        <PlayerList :room-id="roomId" :max-players="maxPlayers" />
      </div>
      
      <!-- 中央画布区域 -->
      <div class="game-canvas-area">
        <GameCanvas 
          ref="gameCanvasRef"
          :room-id="roomId"
          @area-updated="handleAreaUpdated"
        />
      </div>
      
      <!-- 右侧游戏信息 -->
      <div class="game-info">
        <div class="info-card">
          <h3>游戏状态</h3>
          <div class="status-item">
            <span class="label">状态:</span>
            <span class="value" :class="gameStatusClass">{{ gameStatusText }}</span>
          </div>
          <div class="status-item">
            <span class="label">玩家数:</span>
            <span class="value">{{ players.length }}/{{ maxPlayers }}</span>
          </div>
          <div class="status-item">
            <span class="label">剩余时间:</span>
            <span class="value">{{ formatTime(timeLeft) }}</span>
          </div>
        </div>
        
        <div class="info-card">
          <h3>实时统计</h3>
          <div class="stats-list">
            <div
              v-for="(player, index) in sortedPlayers"
              :key="player.id"
              class="stat-item"
              :class="{ 'current-player': player.id === currentPlayerId }"
            >
              <div class="stat-rank">{{ index + 1 }}</div>
              <div class="stat-avatar">
                <div 
                  class="avatar-color" 
                  :style="{ backgroundColor: player.color }"
                ></div>
              </div>
              <div class="stat-info">
                <div class="stat-name">{{ player.nickname }}</div>
                <div class="stat-area">{{ formatArea(player.id) }} 像素</div>
              </div>
              <div class="stat-percentage">
                {{ calculatePercentage(player.id) }}%
              </div>
            </div>
          </div>
        </div>
        
        <div class="info-card">
          <h3>游戏控制</h3>
          <div class="control-buttons">
            <el-button 
              @click="pauseGame" 
              :disabled="gameStatus !== 'playing'"
              type="warning"
              size="large"
            >
              <el-icon><VideoPause /></el-icon>
              暂停游戏
            </el-button>
            
            <el-button 
              @click="endGame" 
              type="danger"
              size="large"
            >
              <el-icon><VideoPlay /></el-icon>
              结束游戏
            </el-button>
            
            
          </div>
        </div>
      </div>
    </div>

    <!-- 游戏结束弹窗 -->
    <el-dialog
      v-model="showGameEndDialog"
      title="游戏结束"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="game-end-content">
        <div class="winner-section">
          <div class="winner-avatar">
            <div 
              class="avatar-color" 
              :style="{ backgroundColor: endWinner?.color }"
            ></div>
          </div>
          <h2 class="winner-title">🏆 获胜者</h2>
          <p class="winner-name">{{ endWinner?.nickname }}</p>
          <p class="winner-area">占领面积: {{ formatAreaValue(endWinner?.area) }} 像素</p>
        </div>
        
        <div class="final-rankings">
          <h3>最终排名</h3>
          <div class="rankings-list">
            <div
              v-for="(player, index) in finalRanking"
              :key="player.id"
              class="ranking-item"
              :class="{ 'winner': index === 0 }"
            >
              <div class="ranking-position">{{ index + 1 }}</div>
              <div class="ranking-avatar">
                <div 
                  class="avatar-color" 
                  :style="{ backgroundColor: player.color }"
                ></div>
              </div>
              <div class="ranking-info">
                <div class="ranking-name">{{ player.nickname }}</div>
                <div class="ranking-area">{{ formatAreaValue(player.area) }} 像素</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="backToLobby" type="primary" size="large">
            返回大厅
          </el-button>
          <el-button @click="playAgain" type="success" size="large">
            返回房间
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Connection, VideoPause, VideoPlay 
} from '@element-plus/icons-vue'
import { useGameStore } from '@/stores/game'
import { createSignalRService } from '@/services/socketService'
import { addHistoryRecord } from '@/utils/gameHistory'
import GameCanvas from '@/components/GameCanvas.vue'
import PlayerList from '@/components/PlayerList.vue'
import GameTimer from '@/components/GameTimer.vue'

const props = defineProps({
  roomId: {
    type: String,
    required: true
  }
})

const router = useRouter()
const gameStore = useGameStore()
const signalRService = createSignalRService(gameStore)

// 引用
const gameCanvasRef = ref()

// 状态
const showGameEndDialog = ref(false)
const finalRanking = ref([])
const endWinner = ref(null)

// 计算属性
const roomName = computed(() => gameStore.currentRoom?.name || `房间 ${props.roomId}`)
const maxPlayers = computed(() => gameStore.currentRoom?.maxPlayers || 6)
const players = computed(() => gameStore.players)
const gameStatus = computed(() => gameStore.gameStatus)
const timeLeft = computed(() => Number(gameStore.timeLeft || 0))
const gameDuration = computed(() => gameStore.gameDuration)
const currentPlayerId = computed(() => gameStore.currentPlayer?.id)
const isConnected = computed(() => gameStore.isConnected)
const sortedPlayers = computed(() => gameStore.sortedPlayers)
const winner = computed(() => gameStore.winner)

const gameStatusText = computed(() => {
  switch (gameStatus.value) {
    case 'waiting': return '等待开始'
    case 'playing': return '游戏中'
    case 'finished': return '游戏结束'
    default: return '未知状态'
  }
})

const gameStatusClass = computed(() => {
  switch (gameStatus.value) {
    case 'waiting': return 'status-waiting'
    case 'playing': return 'status-playing'
    case 'finished': return 'status-finished'
    default: return ''
  }
})

// 在组件挂载时初始化SignalR服务
onMounted(() => {
  console.log('Game组件挂载，当前玩家信息:', gameStore.currentPlayer)
  console.log('房间ID:', props.roomId)
  
  initializeGame()
  setupGameListeners()
  
  // 确保当前玩家信息存在
  if (!gameStore.currentPlayer) {
    console.warn('当前玩家信息不存在，尝试从localStorage恢复')
    const savedPlayer = localStorage.getItem('currentPlayer')
    if (savedPlayer) {
      try {
        const player = JSON.parse(savedPlayer)
        gameStore.setCurrentPlayer(player)
        console.log('从localStorage恢复的玩家信息:', player)
      } catch (error) {
        console.error('解析保存的玩家信息失败:', error)
      }
    }
  }
})

onUnmounted(() => {
  removeGameListeners()
})

// 监听游戏状态变化
watch(gameStatus, (newStatus) => {
  if (newStatus === 'finished') {
    showGameEndDialog.value = true
  }
})

function initializeGame() {
  // 确保已连接到房间
  if (!isConnected.value) {
    signalRService.connect()
  }
}

function setupGameListeners() {
  // 监听游戏相关事件
  signalRService.on('GameEnded', handleGameEnded)
  signalRService.on('AreaUpdated', handleAreaUpdated)
}

function removeGameListeners() {
  signalRService.off('GameEnded', handleGameEnded)
  signalRService.off('AreaUpdated', handleAreaUpdated)
}

function handleGameEnded(finalResults) {
  showGameEndDialog.value = true
  try {
    const room = gameStore.currentRoom || { id: props.roomId, name: `房间 ${props.roomId}` }
    const duration = Number(gameStore.gameDuration || 0)
    const playersSnapshot = (gameStore.players || []).map(p => ({ id: p.id, nickname: p.nickname, color: p.color }))
    const areas = playersSnapshot.map(p => ({ playerId: p.id, area: Number(gameStore.playerAreas.get(p.id) || 0) }))
    const sorted = [...areas].sort((a, b) => Number(b.area) - Number(a.area))
    const winnerPlayerId = sorted[0]?.playerId
    const winnerPlayer = (gameStore.players || []).find(p => p.id === winnerPlayerId) || null

    // 结束时快照用于弹窗的稳定排名展示
    const finalRankingSnapshot = playersSnapshot
      .map(p => ({ ...p, area: Number(gameStore.playerAreas.get(p.id) || 0) }))
      .sort((a, b) => Number(b.area) - Number(a.area))
    finalRanking.value = finalRankingSnapshot
    endWinner.value = finalRankingSnapshot[0] || null

    addHistoryRecord({
      roomId: room.id,
      roomName: room.name,
      endedAt: Date.now(),
      durationSeconds: duration,
      players: playersSnapshot,
      areas,
      winner: winnerPlayer ? { id: winnerPlayer.id, nickname: winnerPlayer.nickname, color: winnerPlayer.color } : null
    })
  } catch (e) {
    // 忽略
  }
}

function handleAreaUpdated(areaData) {
  console.log('收到面积更新事件:', areaData)
  
  // 如果是从GameCanvas组件发来的单个面积数据
  if (areaData && typeof areaData === 'object' && !Array.isArray(areaData)) {
    // 这里可以处理单个面积更新
    console.log('单个面积更新:', areaData)
    return
  }
  
  // 如果是从SignalR发来的面积统计数组
  if (Array.isArray(areaData)) {
    areaData.forEach(stat => {
      gameStore.updatePlayerArea(stat.playerId, stat.area)
    })
  }
}

function backToLobby() {
  // 主动从房间退出并断开连接，避免房间残留离线玩家
  const playerId = gameStore.currentPlayer?.id
  try {
    if (playerId) {
      signalRService.leaveRoom(props.roomId, playerId)
    }
  } catch (e) {
    // 忽略离开失败
  }
  try {
    signalRService.disconnect()
  } catch (e) {
    // 忽略断开失败
  }
  router.push(`/`)
}

function pauseGame() {
  // 发送暂停游戏命令
  signalRService.sendPaintAction(props.roomId, {
    type: 'pauseGame',
    timestamp: Date.now()
  })
  
  ElMessage.info('游戏已暂停')
}

function endGame() {
  ElMessageBox.confirm(
    '确定要结束游戏吗？',
    '确认结束',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 调用服务端 EndGame，触发持久化历史记录
    signalRService.endGame(props.roomId)
  }).catch(() => {
    // 用户取消
  })
}

function playAgain() {
  showGameEndDialog.value = false
  
  // 重置游戏状态
  gameStore.resetGame()
  
  // 清空画布
  if (gameCanvasRef.value) {
    gameCanvasRef.value.clearCanvas()
  }
  
  // 返回房间并主动刷新房间信息，清除已退出的玩家
  router.push(`/room/${props.roomId}`)
}

function formatTime(seconds) {
  if (!seconds) return '00:00'
  
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

function formatArea(playerId) {
  if (!playerId) return '0'
  const area = Number(gameStore.playerAreas.get(playerId) || 0)
  return Number.isFinite(area) ? area.toLocaleString() : '0'
}

function formatAreaValue(area) {
  const value = Number(area || 0)
  if (value >= 1000000) {
    return `${(value / 1000000).toFixed(1)}M`
  } else if (value >= 1000) {
    return `${(value / 1000).toFixed(1)}K`
  }
  return Math.round(value).toLocaleString()
}

function calculatePercentage(playerId) {
  if (!playerId) return 0
  
  const playerArea = Number(gameStore.playerAreas.get(playerId) || 0)
  const totalArea = Number(gameStore.totalArea || 0)
  
  if (!Number.isFinite(totalArea) || totalArea <= 0) return 0
  const percent = (playerArea / totalArea) * 100
  return Number.isFinite(percent) ? Math.round(percent) : 0
}

function testCanvasSync() {
  if (gameCanvasRef.value) {
    // 已移除测试同步功能
  }
}
</script>

<style scoped>
.game-container {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.game-header {
  background: white;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.room-info h2 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 1.5rem;
}

.room-code {
  background: #f0f0f0;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  color: #666;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  background: #ff4d4f;
  color: white;
  font-size: 14px;
}

.connection-status.connected {
  background: #52c41a;
}

.game-main {
  flex: 1;
  display: grid;
  grid-template-columns: 350px 1fr 350px;
  gap: 20px;
  padding: 20px;
  min-height: calc(100vh - 100px);
}

.game-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.game-canvas-area {
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.game-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.info-card h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 1.2rem;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.status-item .label {
  color: #666;
  font-weight: 500;
}

.status-item .value {
  font-weight: 600;
  color: #333;
}

.value.status-waiting {
  color: #faad14;
}

.value.status-playing {
  color: #52c41a;
}

.value.status-finished {
  color: #ff4d4f;
}

.stats-list {
  max-height: 300px;
  overflow-y: auto;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: #f0f0f0;
}

.stat-item.current-player {
  background: #e6f7ff;
  border: 2px solid #1890ff;
}

.stat-rank {
  width: 30px;
  height: 30px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 12px;
}

.stat-avatar {
  margin-right: 12px;
}

.avatar-color {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-info {
  flex: 1;
}

.stat-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stat-area {
  font-size: 12px;
  color: #666;
}

.stat-percentage {
  font-weight: 600;
  color: #1890ff;
  font-size: 14px;
}

.control-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.control-buttons .el-button {
  width: 100%;
}

.game-end-content {
  text-align: center;
}

.winner-section {
  margin-bottom: 30px;
}

.winner-avatar {
  margin-bottom: 20px;
}

.winner-avatar .avatar-color {
  width: 80px;
  height: 80px;
  margin: 0 auto;
}

.winner-title {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 1.5rem;
}

.winner-name {
  margin: 0 0 5px 0;
  font-size: 1.2rem;
  color: #1890ff;
  font-weight: 600;
}

.winner-area {
  margin: 0;
  color: #666;
}

.final-rankings h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 1.2rem;
}

.rankings-list {
  max-height: 200px;
  overflow-y: auto;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 8px;
  background: #fafafa;
}

.ranking-item.winner {
  background: #f6ffed;
  border: 2px solid #52c41a;
}

.ranking-position {
  width: 24px;
  height: 24px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  margin-right: 12px;
}

.ranking-item.winner .ranking-position {
  background: #52c41a;
}

.ranking-avatar {
  margin-right: 12px;
}

.ranking-avatar .avatar-color {
  width: 28px;
  height: 28px;
}

.ranking-info {
  flex: 1;
}

.ranking-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.ranking-area {
  font-size: 12px;
  color: #666;
}

.dialog-footer {
  text-align: center;
}

.dialog-footer .el-button {
  margin: 0 10px;
}

@media (max-width: 1200px) {
  .game-main {
    grid-template-columns: 300px 1fr 300px;
  }
}

@media (max-width: 992px) {
  .game-main {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .game-sidebar,
  .game-info {
    order: 2;
  }
  
  .game-canvas-area {
    order: 1;
  }
}

@media (max-width: 768px) {
  .game-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .header-left {
    flex-direction: column;
    gap: 10px;
  }
  
  .game-main {
    padding: 15px;
  }
}
</style>
